package com.yxp423.ssmempl.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import cn.hutool.cache.impl.LFUCache;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxp423.ssmempl.bean.City;
import com.yxp423.ssmempl.bean.Province;
import com.yxp423.ssmempl.bean.Travel;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.bean.dto.UserOnline;
import com.yxp423.ssmempl.dto.TravelDto;
import com.yxp423.ssmempl.service.IRegionsService;
import com.yxp423.ssmempl.service.ISessionService;
import com.yxp423.ssmempl.service.ITravelService;
import com.yxp423.ssmempl.service.IUserService;
import com.yxp423.ssmempl.service.impl.RedisService;
import com.yxp423.ssmempl.service.impl.SessionServiceImpl;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import com.yxp423.ssmempl.utils.consts.ApplyConst;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-05-04 12:25
 * @Version: 1.0
 */
@Controller
@RequestMapping("travel")
public class TravelController {

	@Autowired
	ITravelService travelService;
	@Autowired
	IRegionsService regionsService;
	@Autowired
	IUserService userService;
	@Autowired
	ISessionService sessionService;

	@Autowired
	RedisService redisService;


	//	FIFOCache<String, IPage> travelPagesCache = CacheUtil.newFIFOCache(100, 100000);
//	FIFOCache<String, User> travelUsersCache = CacheUtil.newFIFOCache(10, 100000);
	private Cache<String, IPage> travelPagesCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);
	private Cache<String, User> travelUsersCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);

	@RequestMapping("applytravel")
	public String applyTravel() {


		return "travel/apply_travel";
	}

	/**
	 * 跳转我的外出页面
	 *
	 * @return
	 */
	@GetMapping("/mytravel")
	public String toMyTravelPage() {

		return "travel/my_travel";

	}

	@GetMapping("/reviewtravel")
	public String toReviewTravelPage() {
		return "travel/review_travel";
	}


	@GetMapping("/submitApply")
	@ResponseBody
	public AjaxResult submitApply(Travel travel, String provinceId, String cityId) {

		AjaxResult result = new AjaxResult();
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		Province province = regionsService.getProvinceById(provinceId);
		City city = regionsService.getCityById(cityId);

		travel.setUserId(user.getUserId().toString());
		travel.setCreatTime(new Date());
		travel.setPlace(province.getName() + city.getName());
		travel.setReviewStatus(ApplyConst.STATUS_CHECKING);

		int flag = -1;
		try {
			flag = travelService.saveTravel(travel);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMsg(e.toString());

		}

		if (flag > 0) {
			result.setSuccess(true);
			result.setMsg("保存成功");
		}


		return result;
	}


	@GetMapping("myapplytravel")
	@ResponseBody
	public AjaxResult myApplyTravel(Page page) {


		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		User reviewer = null;

		if (redisService.get("user-" + user.getUserId() + "travelListPage" + page.getCurrent()) != null) {

			result.setSuccess(true);
			result.setData(redisService.get("user-" + user.getUserId() + "travelListPage" + page.getCurrent()));
			return result;
		}
		User user1 = (User) redisService.get("user1");
		System.out.println(user1);
		IPage<Travel> myTravel = travelService.getMyTravel(page, user);

		if (ObjectUtil.isNotEmpty(myTravel)) {

			for (Travel travels : myTravel.getRecords()) {

				travels.setUserName(user.getName());

				if (redisService.get("user" + travels.getReviewerId()) == null) {


					reviewer = userService.getUserById(Integer.parseInt(travels.getReviewerId()));//获取审核人名字
					if (reviewer != null) {

						redisService.set("user" + travels.getReviewerId(), reviewer);
					}
				} else {
					reviewer = (User) redisService.get("user" + travels.getReviewerId());
				}

				travels.setReviewerName(reviewer.getName());

			}
			result.setSuccess(true);
			result.setData(myTravel);
			redisService.set("user-" + user.getUserId() + "travelListPage" + page.getCurrent(), myTravel);

		} else {
			result.setSuccess(false);
			result.setMsg("无数据");
		}
		return result;
	}


	@GetMapping("/getmyreviewtravel")
	@ResponseBody
	public AjaxResult getMyReviewTravel(Page page) {
		AjaxResult result = new AjaxResult();

//		long startTime = DateUtil.current(true);

		try {
			//先判断有没有该页的缓存，没有则进入数据库查询，有则直接读取缓存
			if (ObjectUtil.isNull(travelPagesCache.get("page" + page.getCurrent()))) {

				User user = (User) SecurityUtils.getSubject().getPrincipal();//当前登录用户

				IPage<Travel> applys = travelService.getMyReviewTravel(page, user);//获取审核人为当前用户的申请并分页

				if (ObjectUtil.isNotNull(applys)) {

					for (Travel record : applys.getRecords()) {

						if (travelUsersCache.get("user" + record.getUserId()) == null) {

							User applyer = userService.getUserById(Integer.parseInt(record.getUserId()));

							record.setUserName(applyer.getName());
							record.setReviewerName(user.getName());

							travelUsersCache.put("user" + record.getUserId(), applyer);

						} else {

							record.setUserName(travelUsersCache.get("user" + record.getUserId()).getName());
							record.setReviewerName(user.getName());

						}

					}

					result.setSuccess(true);
					result.setMsg("获取数据成功");
					result.setData(applys);
					travelPagesCache.put("page" + page.getCurrent(), applys); //写入缓存

				} else {

					result.setSuccess(false);
					result.setMsg("获取分页数据失败");
				}

			} else {

				result.setSuccess(true);
				result.setData(travelPagesCache.get("page" + page.getCurrent()));

			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("发生错误，错误为" + e.toString());
		}

//		System.out.println(DateUtil.spendNt(startTime));
		return result;
	}


	@GetMapping("/reviewTravel")
	@ResponseBody
	/**
	 * 审核单个日志
	 */
	public AjaxResult reviewTravel(Travel travel) {
		AjaxResult result = travelService.updateTravel(travel);

		travelPagesCache.clear();//清空分页缓存

		return result;
	}


	@GetMapping("/reviewBatch")
	@ResponseBody
	public AjaxResult reviewBatch(List<Travel> lists) {
		AjaxResult result = new AjaxResult();

		return result;
	}

}
